﻿// -----------------------------------------------------------------------
// <copyright file="ComparerForm.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Sitecore.ChangesTracker.UI
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using Sitecore.Shell.Applications.ContentManager;
  using Sitecore.Web.UI.HtmlControls;
  using System.Collections;
  using Sitecore.Web;
  using Sitecore.Text;
  using Sitecore.Configuration;
  using Sitecore.Diagnostics;
  using Sitecore.Data;
  using Sitecore.Data.Items;
  using Sitecore.ChangesTracker.Archiving;
  using Sitecore.Data.Archiving;
  using Sitecore.Globalization;
  using Sitecore.Web.UI.Sheer;
  using Sitecore.Web.Configuration;
  using Sitecore.Shell;
  using Sitecore.Data.Validators;

  /// <summary>
  /// TODO: Update summary.
  /// </summary>
  public class ComparerForm : Sitecore.Web.UI.Sheer.ApplicationForm
  {

    // Fields
    private FieldEditorOptions _options;
    private string _validatorsKey;
    protected System.Web.UI.HtmlControls.HtmlGenericControl Body;
    protected System.Web.UI.WebControls.PlaceHolder BrowserTitle;
    protected Border ContentEditor;
    protected ThemedImage DialogIcon;
    protected Literal DialogText;
    protected Literal DialogTitle;
    protected System.Web.UI.WebControls.PlaceHolder DocumentType;
    protected System.Web.UI.WebControls.PlaceHolder Stylesheets;

    protected override void OnLoad(EventArgs e)
    {
      base.OnLoad(e);
      string formValue = WebUtil.GetFormValue("scSections");
      if (!Context.ClientPage.IsEvent)
      {
        string str2;
        System.Web.UI.AttributeCollection attributes;

        this._options = FieldEditorOptions.Parse(new UrlString(WebUtil.GetQueryString()));
        this.SetDocumentType();
        (attributes = this.Body.Attributes)["class"] = attributes["class"] + " " + UIUtil.GetBrowserClassString();
        int num = Settings.Validators.AutomaticUpdate ? Settings.Validators.UpdateDelay : 0;
        System.Web.UI.Control control = Context.ClientPage.FindControl("ComparerForm");
        Assert.IsNotNull(control, "Form \"ComparerForm\" not found.");
        if (WebUtil.GetQueryString("mo") == "preview")
        {
          str2 = "Shell";
        }
        else
        {
          str2 = "CE_" + ID.NewID.ToShortID();
        }
        control.Controls.Add(new System.Web.UI.LiteralControl(string.Format("<input id=\"__FRAMENAME\" name=\"__FRAMENAME\" type=\"hidden\" value=\"{0}\"/>", str2)));
      }


    }

    protected void OnPreRendered(EventArgs e)
    {
      Assert.ArgumentNotNull(e, "e");
      ComparerEventArgs args = e as ComparerEventArgs;
      Assert.IsNotNull(args, "args cannot be null");
      this.UpdateEditor(args.ArchivalId, args.DbItem, args.ControlPointItem);
      Context.ClientPage.Modified = false;
    }

    private void RenderEditor(Border parent, Guid archivalId, ViewItemInfo db, ViewItemInfo cp)
    {
      Assert.ArgumentNotNull(parent, "parent");
      string id = WebUtil.GetQueryString("arc_id");
      Item i = null;
      if (!string.IsNullOrEmpty(id))
      {
         ChangeTrackerArchive archive = (ChangeTrackerArchive)ArchiveManager.Providers["changetracker"].GetArchive("changetracker", Sitecore.Context.ContentDatabase);
        ArchivedItem arcItem = archive.GetArchivedItems(archivalId, true).FirstOrDefault();
        Assert.IsNotNull(arcItem, "Archived item not found, archivalId:" + id);
        i = Sitecore.Context.ContentDatabase.GetItem(Sitecore.Data.ID.Parse(arcItem.ItemId), Language.Parse(db.Lnaguage), db.Version == 0 ? Sitecore.Data.Version.Latest : Sitecore.Data.Version.Parse(db.Version));
        ListString versions = new ListString();
        foreach (ArchivedField fld in arcItem.Fields)
        {
            if (fld.Version != 0 && !versions.Contains(fld.Version.ToString()) && fld.Language == WebUtil.GetSessionString("arc_lang_cp", Context.ContentLanguage.Name))
            {
                ArchivedField af = arcItem.Fields.FirstOrDefault(f => f.FieldId == FieldIDs.UpdatedBy.Guid && f.Version == fld.Version);
                af = arcItem.Fields.FirstOrDefault(f => f.FieldId == FieldIDs.UpdatedBy.Guid && f.Version == fld.Version);
                if (af != null)
                {
                    versions.AddAt(0,af.Value);
                }
                af = arcItem.Fields.FirstOrDefault(f => f.FieldId == FieldIDs.Updated.Guid && f.Version == fld.Version);
                if (af != null)
                {
                    versions.AddAt(0,af.Value);
                }
                versions.AddAt(0,fld.Version.ToString());
            }
        }

        WebUtil.SetSessionValue("versions", versions.ToString());
        WebUtil.SetSessionValue("languages", arcItem.Languages.ToString());
        ComparerPreview editor = new ComparerPreview();
        editor.RenderWarnings = false;
        editor.RenderHeader = false;
        editor.RenderTabsAndBars = false;
        ChangeTrackerArchiveEntry entry = archive.GetSingleEntry(archivalId);
        editor.RenderComparer(i, arcItem, parent, cp,entry);
      }
      if (Context.ClientPage.IsEvent)
      {
        SheerResponse.SetInnerHtml("ContentEditor", parent);
      }
    }


    private void SetDocumentType()
    {
      string text = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";
      DeviceCapabilities capabilities = Client.Device.Capabilities;
      if (capabilities != null)
      {
        text = StringUtil.GetString(new string[] { capabilities.GetDefaultDocumentType(), text });
      }
      this.DocumentType.Controls.Add(new System.Web.UI.LiteralControl(text));
    }

    private void UpdateEditor(Guid archivalid, ViewItemInfo db, ViewItemInfo cp)
    {
      if (!Context.ClientPage.IsEvent)
      {
        Border control = new Border();
        this.ContentEditor.Controls.Clear();
        control.ID = "Editors";
        Context.ClientPage.AddControl(this.ContentEditor, control);
        this.RenderEditor(control, archivalid, db, cp);
      }
    }


    protected void ValidateItem()
    {
      Assert.IsTrue(UserOptions.ContentEditor.ShowValidatorBar, "Validator bar is switched off in Content Editor");
      string formValue = WebUtil.GetFormValue("scValidatorsKey");
      ValidatorCollection validators = ValidatorManager.GetValidators(ValidatorsMode.ValidatorBar, formValue);
      ValidatorOptions options = new ValidatorOptions(false);
      ValidatorManager.Validate(validators, options);
      string text = ValidatorBarFormatter.RenderValidationResult(validators);
      SheerResponse.Eval(string.Concat(new object[] { "scContent.renderValidators(", StringUtil.EscapeJavascriptString(text), ",", Settings.Validators.UpdateFrequency, ")" }));
    }

    // Properties
    public Hashtable FieldInfo
    {
      get
      {
        Hashtable hashtable = base.ServerProperties["Info"] as Hashtable;
        if (hashtable == null)
        {
          hashtable = new Hashtable(5);
          base.ServerProperties["Info"] = hashtable;
        }
        return hashtable;
      }
    }

  }
}
